from logging import log
import os
import re
from PIL import Image
from .pre_config_brower import request_fun
from .getConfig import getConfig, logger
parent_save_path = getConfig().get('Image', 'save_path')


class downloadImage:
    @staticmethod
    def format_img_name(url=None, name=None):
        if not name:
            name = url.strip().split('/')[-1]
            name = name.split('?')[0]
        else:
            name = re.sub('([\"\',/| ])', "_", name)

        if name[-4] != ".":
            name += ".jpg"
        return name

    @staticmethod
    def download(pic_url, pic_name, save_img_dir_path):
        status = "fail"
        img_full_path_name = os.path.join(save_img_dir_path, pic_name)
        if pic_name in os.listdir(save_img_dir_path):
            pass
        else:
            try:
                img = request_fun(pic_url.strip())
                with open(img_full_path_name, 'wb') as p:
                    p.write(img)
                with Image.open(img_full_path_name) as jpg:
                    if jpg.size and jpg.size[0]:
                        pass
                    else:
                        logger.error("donwload Error[pic size]: %s" % pic_url)
                        return status

                    if jpg.format == "WEBP":
                        jpg.save(img_full_path_name, "JPEG")
            except Exception as e:
                logger.error(e)
                return status

        status = "ok"
        return status

    @staticmethod
    def imgs_save_path(companyName, category, img_name=None):
        save_img_path = os.path.join(parent_save_path,
                                     companyName,
                                     category)

        if not os.path.exists(save_img_path):
            os.makedirs(save_img_path)
        if img_name:
            return os.path.join(save_img_path, img_name)

        return save_img_path

    @staticmethod
    def check_download_status(sql_instance, company, category, table="productList"):
        def query_count(productImageStatus=""):
            query_cmd = "select count(*) from {table} \
                        where companyName='{company}' and \
                        category='{category}' \
                        {productImageStatus} \
                        ".format(table=table,
                                 company=company,
                                 category=category,
                                 productImageStatus=productImageStatus)
            query_rep = sql_instance.executor(query_cmd)
            return query_rep[0].get("count(*)")

        total_num = query_count()
        done_num = query_count("and productImageStatus='ok'")
        logger.info("Total num: %s, download complete: %s" %
                    (total_num, done_num))

        if total_num == done_num:
            return True
